import time
import hashlib
import csv
import requests



def is_number(s):
    try:  # 如果能运行float(s)语句，返回True（字符串s是浮点数）
        float(s)
        return True
    except ValueError:  # ValueError为Python的一种标准异常，表示"传入无效的参数"
        pass  # 如果引发了ValueError这种异常，不做任何事情（pass：不做任何事情，一般用做占位语句）
    try:
        import unicodedata  # 处理ASCii码的包
        unicodedata.numeric(s)  # 把一个表示数字的字符串转换为浮点数返回的函数
        return True
    except (TypeError, ValueError):
        pass
    return False


wts = int(time.time())
# u=['ids=2837%2C2836%2C2870%2C2953%2C2954%2C2955%2C2956%2C5672', 'pf=0', 'wts=1710828406']
u = [
    'ids=2837%2C2836%2C2870%2C2953%2C2954%2C2955%2C2956%2C5672',
    'pf=0',
    f'wts={wts}'
]
m = '&'.join(u)
o = 'ea1db124af3c7062474693fa704f4ff8'
string = m + o
md = hashlib.md5(string.encode())  # 創建md5對象
w_rid = md.hexdigest()
fp = open('./B站Top100综合热门视频.csv', 'a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(fp, fieldnames=['标题', '视频号', '作者', '点赞', '投币', '转发', '播放量', '评论','评分'])
csv_writer.writeheader()
for page in range(1, 6):
    url = f'https://api.bilibili.com/x/web-interface/popular?ps=20&pn={page}&web_location=333.934&w_rid={w_rid}&wts={wts}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0'
    }
    json_data = requests.get(url=url, headers=headers).json()
    list = json_data['data']['list']
    for li in list:
        title = li['title']  # 标题
        aid = li['stat']['aid']  # 视频号
        owner = li['owner']['name']  # 作者
        favorite = li['stat']['favorite']  # 点赞
        coin = li['stat']['coin']  # 投币
        share = li['stat']['share']  # 转发
        view = li['stat']['view']  # 播放量
        reply = li['stat']['reply']  # 评论
        point = favorite / view + coin * 10 / favorite + reply * 100 / view
        dic = {
            '标题': title,
            '视频号': aid,
            '作者': owner,
            '点赞': favorite,
            '投币': coin,
            '转发': share,
            '播放量': view,
            '评论': reply,
            '评分': point
        }
        csv_writer.writerow(dic)

csv_reader = csv.DictReader(open("B站Top100综合热门视频.csv",encoding='utf-8'))
dictPoint = {}
for row in csv_reader:
    dictPoint[row['标题']] = row['评分']
    if is_number(row['评分']):
        dictPoint[row['标题']] = float(row['评分'])
    else:
        dictPoint.pop(row['标题'])

print(sorted(dictPoint.items(), key = lambda kv:(kv[1], kv[0])))
